package com.mq.exchange;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * 发布订阅:扇出交换
 *
 * @author xwj
 * @date 2019/2/28
 */
public class ReceiveLogsFanout {
    /**
     * 交换机名称
     */
    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        // 声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        //创建一个非持久化的、独有的并且是自动删除的已命名的queue
        String queueName = channel.queueDeclare().getQueue();
        // 绑定exchange和queue
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        System.out.println("Waiting for log");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received log:" + message);
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}
